import type { FormInstance, UploadFile } from 'element-plus'
import type { tenantUserEnum, orderQualityServiceEnum } from '~/store/oam/typings'
import type {
  OptionButtonEventPropsType,
  OptionButtonEventFormValuesType,
  OptionButtonEventStateType
} from './typings'
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import {
  ElMessageBox,
  ElMessage,
  ElDialog,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElCheckboxGroup,
  ElCheckbox,
  ElButton,
  ElIcon
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import InputTextarea from '~/components/ProForm/InputTextarea'
import BaseUpload from '~/components/ProForm/BaseUpload'
import OrdersUpdate from '../opeHomepage/OrdersUpdate'
import useVuexGetters from '~/hooks/useVuexGetters'

// clickOptionButtonType.operationType 有值或者 record有值则是待办操作，如果两个都没值就是工单操作
export default function OptionButtonEvent(props: OptionButtonEventPropsType) {
  const { detail, record, clickOptionButtonType, cancel } = props
  const store = useStore()
  const visibleRef = ref<boolean>(true)
  const elFormRef = ref<FormInstance>()
  const state = reactive<OptionButtonEventStateType>({
    faultReasonCheckboxList: []
  })
  // 是工单处理时初始化两个上传框数组
  const formValues = reactive<OptionButtonEventFormValuesType>(
    clickOptionButtonType?.identType === 'order_handle'
      ? {
          handleBeforImage: [],
          handleAfterImage: []
        }
      : {}
  )
  const orderState = useVuexGetters('order', [
    'handleUserSelectList',
    'orderQualityServiceSelectList'
  ])
  // 工单回退
  const handleOrderBack = () => {
    const titleStr = {
      // 待确认
      1: '工单回退至监控中心',
      // 待处理
      2: '工单回退至待确认',
      // 待终结
      3: '工单回退至待处理',
      // 待归档
      4: '工单回退至待终结'
    }[detail?.orderStatus!]
    ElMessageBox.prompt('请输入工单回退原因', titleStr, {
      inputPlaceholder: '请输入工单回退原因',
      inputValidator: (value: string) => {
        if (!value) return '请输入工单回退原因'
        return true
      }
    })
      .then(({ value }) => {
        // 待办逻辑
        if (clickOptionButtonType?.operationType && record) {
          const params = {
            taskId: record?.taskId,
            operationType: clickOptionButtonType?.operationType,
            message: value
          }
          store.dispatch('toDo/BackOrderFlowTask', params).then((res) => {
            if (res?.code === 200) {
              ElMessage({
                type: 'success',
                message: '操作成功'
              })
              cancel()
            }
          })
          return
        }
        // 工单逻辑
        store
          .dispatch('order/PostOrderBack', { backReson: value, orderId: detail?.id })
          .then((res) => {
            if (res?.code === 200) {
              ElMessage({
                type: 'success',
                message: '操作成功'
              })
              cancel()
            }
          })
      })
      .catch(() => {})
  }
  // 工单分配(确认)
  const handleOrderConfirm = () => {
    if (!elFormRef?.value) return
    elFormRef?.value.validate(async (valid) => {
      if (!valid) return
      // 待办操作
      if (clickOptionButtonType?.operationType && record) {
        const params = {
          businessFrom: {
            ...formValues,
            id: detail?.id
          },
          operationType: clickOptionButtonType?.operationType,
          taskId: record?.taskId,
          values: {
            appointedAssignee: formValues?.handleUserId
          }
        }
        const res = await store.dispatch('toDo/SubmitOrderFlowTask', params)
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          cancel()
        }
        return
      }
      // 工单操作
      const params = {
        ...detail,
        ...formValues
      }
      const res = await store.dispatch('order/PostOrderConfirm', params)
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '操作成功' })
        cancel()
      }
    })
  }
  // 工单处理
  const handleOrderHandle = () => {
    if (!elFormRef?.value) return
    elFormRef?.value.validate(async (valid) => {
      if (!valid) return
      const params = {
        businessFrom: {
          id: detail?.id,
          ...formValues,
          faultReason: (formValues?.faultReason as string[])?.join(','),
          handleBeforImage: (formValues?.handleBeforImage as string[])?.join(','),
          handleAfterImage: (formValues?.handleAfterImage as string[])?.join(',')
        },
        taskId: record?.taskId,
        operationType: clickOptionButtonType?.operationType
      }
      const res = await store.dispatch('toDo/SubmitOrderFlowTask', params)
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '操作成功' })
        cancel()
      }
    })
  }
  // 终结工单
  const handleOrderOver = () => {
    ElMessageBox.confirm('是否终结工单, 确认工单已处理完成?', '确认提示', {
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(() => {
        // 待办操作
        if (clickOptionButtonType?.operationType && record) {
          const params = {
            taskId: record?.taskId,
            operationType: clickOptionButtonType?.operationType,
            businessFrom: {
              id: detail?.id
            }
          }
          store.dispatch('toDo/SubmitOrderFlowTask', params).then((res) => {
            if (res?.code === 200) {
              ElMessage({
                type: 'success',
                message: '操作成功'
              })
              cancel()
            }
          })
          return
        }
        // 工单逻辑
        const params = {
          ...detail,
          ...formValues
        }
        store.dispatch('order/PostOrderEnd', params).then((res) => {
          if (res?.code === 200) {
            ElMessage({
              type: 'success',
              message: '操作成功'
            })
            cancel()
          }
        })
      })
      .catch(() => {})
  }
  // 工单归档
  const handleOrderPlfile = () => {
    if (!elFormRef?.value) return
    elFormRef?.value.validate(async (valid) => {
      if (!valid) return
      // 待办操作
      if (clickOptionButtonType?.operationType && record) {
        const params = {
          businessFrom: {
            id: detail?.id,
            ...formValues
          },
          taskId: record?.taskId,
          operationType: clickOptionButtonType?.operationType
        }
        const res = await store.dispatch('toDo/SubmitOrderFlowTask', params)
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          cancel()
        }
        return
      }
      // 工单逻辑
      const params = {
        ...detail,
        ...formValues
      }
      const res = await store.dispatch('order/PostOrderRegular', params)
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '操作成功' })
        cancel()
      }
    })
  }
  // 发送工单
  const handleOrderSend = () => {
    ElMessageBox.confirm('确认是否发送工单？', '确认提示', {
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(() => {
        // 待办逻辑
        if (clickOptionButtonType?.operationType && record) {
          const params = {
            taskId: record?.taskId,
            operationType: clickOptionButtonType?.operationType,
            businessFrom: {
              id: detail?.id
            }
          }
          store.dispatch('toDo/SubmitOrderFlowTask', params).then((res) => {
            if (res?.code === 200) {
              ElMessage({
                type: 'success',
                message: '操作成功'
              })
              cancel()
            }
          })
          return
        }
        // 工单逻辑
        store.dispatch('order/PostOrderSend', { id: detail?.id }).then((res) => {
          if (res?.code === 200) {
            ElMessage({
              type: 'success',
              message: '操作成功'
            })
            cancel()
          }
        })
      })
      .catch(() => {})
  }
  // 删除工单
  const handleOrderDelete = () => {
    ElMessageBox.confirm('是否确认删除工单？', '确认提示', {
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(() => {
        // 待办逻辑
        if (clickOptionButtonType?.operationType && record) {
          const params = {
            taskId: record?.taskId,
            operationType: clickOptionButtonType?.operationType,
            businessKey: detail?.id
          }
          store.dispatch('toDo/DeleteOrderFlowTask', params).then((res) => {
            if (res?.code === 200) {
              ElMessage({
                type: 'success',
                message: '操作成功'
              })
              cancel()
            }
          })
          return
        }
        // 工单逻辑
        store.dispatch('order/PostOrderRemove', { ids: detail?.id }).then((res) => {
          if (res?.code === 200) {
            ElMessage({
              type: 'success',
              message: '操作成功'
            })
            cancel()
          }
        })
      })
      .catch(() => {})
  }
  // 完成计划
  const handleCompletePlan = async () => {
    const params = {
      taskId: record?.taskId,
      operationType: clickOptionButtonType?.operationType
    }
    const res = await store.dispatch('toDo/SubmitOrderFlowTask', params)
    if (res?.code === 200) {
      ElMessage({
        type: 'success',
        message: '操作成功'
      })
      cancel()
    }
  }

  // 上传成功回调
  const handleUploadSuccess = (file: Record<string, any>, type: 'before' | 'after') => {
    const link = file?.response?.data?.link
    if (link) {
      if (type === 'before') (formValues.handleBeforImage as string[]).push(link)
      if (type === 'after') (formValues.handleAfterImage as string[]).push(link)
    }
  }
  // 移除对应的文件
  const handleRemoveUploadFile = (file: Record<string, any>, type: 'before' | 'after') => {
    const link = file?.response?.data?.link || file?.url
    if (link) {
      if (type === 'before') {
        formValues.handleBeforImage = (formValues.handleBeforImage as string[])?.filter(
          (item) => item !== link
        )
      }
      if (type === 'after') {
        formValues.handleAfterImage = (formValues.handleAfterImage as string[])?.filter(
          (item) => item !== link
        )
      }
    }
  }

  // 获取故障原因多选列表
  const handleGetFaultReasonCheckboxList = async () => {
    // 请求
    const res = await store.dispatch('order/GetOrderSetList', {
      current: 1,
      size: 1000,
      cfgTypeCode: 4 // 获取故障原因传4
    })
    state.faultReasonCheckboxList = res?.data?.records || []
  }
  // 获取负责人下拉列表
  const handleGetHandleUserSelectList = () => {
    store.dispatch('order/GetConfirmOrderHandleUserSelectList', { orderId: detail?.id })
  }
  ;(function init() {
    // 工单分配查负责人下拉列表
    if (clickOptionButtonType?.identType === 'order_confirm' && detail?.id) {
      handleGetHandleUserSelectList()
    }
    // 处理工单查故障原因多选列表
    if (clickOptionButtonType?.identType === 'order_handle') handleGetFaultReasonCheckboxList()
  })()
  return (
    <>
      {/* 工单回退 */}
      {clickOptionButtonType?.identType === 'order_back' && handleOrderBack()}
      {/* 工单分配(确认) */}
      {clickOptionButtonType?.identType === 'order_confirm' && (
        <ElDialog
          title="工单分配"
          modelValue={visibleRef.value}
          width={300}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={props.clearClickOptionButtonType}
          v-slots={{
            footer: () => (
              <>
                <ElButton onClick={props.clearClickOptionButtonType}>取消</ElButton>
                <ElButton type="primary" onClick={handleOrderConfirm}>
                  确认
                </ElButton>
              </>
            )
          }}
        >
          <ElForm ref={elFormRef} model={formValues}>
            <ElFormItem
              label="负责人"
              prop="handleUserId"
              rules={[{ required: true, message: '请选择负责人', trigger: 'change' }]}
            >
              <ElSelect v-model={formValues.handleUserId}>
                {orderState.handleUserSelectList?.value?.map((item: tenantUserEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id} />
                ))}
              </ElSelect>
            </ElFormItem>
          </ElForm>
        </ElDialog>
      )}
      {/* 处理工单 */}
      {clickOptionButtonType?.identType === 'order_handle' && (
        <ElDialog
          title="工单处理"
          modelValue={visibleRef.value}
          width="50%"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={props.clearClickOptionButtonType}
          v-slots={{
            footer: () => (
              <>
                <ElButton onClick={props.clearClickOptionButtonType}>取消</ElButton>
                <ElButton type="primary" onClick={handleOrderHandle}>
                  确认
                </ElButton>
              </>
            )
          }}
        >
          <ElForm ref={elFormRef} model={formValues}>
            <ElFormItem
              label="故障原因"
              prop="faultReason"
              rules={[{ required: true, message: '请选择故障原因', trigger: 'change' }]}
            >
              <ElCheckboxGroup v-model={formValues.faultReason}>
                {state.faultReasonCheckboxList?.map((item) => (
                  <ElCheckbox label={item?.id}>{item?.cfgTypeName}</ElCheckbox>
                ))}
              </ElCheckboxGroup>
            </ElFormItem>
            <ElFormItem
              label="处理前图片"
              prop="handleBeforImage"
              rules={[{ required: true, message: '请上传处理前图片', trigger: 'change' }]}
            >
              <BaseUpload
                listType="picture-card"
                onSuccess={(response: Record<string, string>, uploadFile: UploadFile) =>
                  handleUploadSuccess(uploadFile, 'before')
                }
                limit={12}
                onRemove={(uploadFile: UploadFile) => handleRemoveUploadFile(uploadFile, 'before')}
              >
                <ElIcon>
                  <Plus />
                </ElIcon>
              </BaseUpload>
            </ElFormItem>
            <ElFormItem
              label="处理内容"
              prop="handleContent"
              rules={[{ required: true, message: '请填写处理内容', trigger: 'change' }]}
            >
              <InputTextarea
                v-model:inputTextareaValue={formValues.handleContent}
                placeholderName="请输入处理内容"
                limitLength={100}
              />
            </ElFormItem>
            <ElFormItem
              label="处理后图片"
              prop="handleAfterImage"
              rules={[{ required: true, message: '请上传处理后图片', trigger: 'change' }]}
            >
              <BaseUpload
                listType="picture-card"
                onSuccess={(response: Record<string, string>, uploadFile: UploadFile) =>
                  handleUploadSuccess(uploadFile, 'after')
                }
                limit={12}
                onRemove={(uploadFile: UploadFile) => handleRemoveUploadFile(uploadFile, 'after')}
              >
                <ElIcon>
                  <Plus />
                </ElIcon>
              </BaseUpload>
            </ElFormItem>
          </ElForm>
        </ElDialog>
      )}
      {/* 工单终结 */}
      {clickOptionButtonType?.identType === 'order_over' && handleOrderOver()}
      {/* 工单归档 */}
      {clickOptionButtonType?.identType === 'order_plfile' && (
        <ElDialog
          title="确认工单是否归档"
          modelValue={visibleRef.value}
          width={500}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={props.clearClickOptionButtonType}
          v-slots={{
            footer: () => (
              <>
                <ElButton onClick={props.clearClickOptionButtonType}>取消</ElButton>
                <ElButton type="primary" onClick={handleOrderPlfile}>
                  确认
                </ElButton>
              </>
            )
          }}
        >
          <ElForm ref={elFormRef} model={formValues}>
            <ElFormItem
              label="优质服务"
              prop="regularState"
              rules={[{ required: true, message: '请勾选优质服务', trigger: 'change' }]}
            >
              <ElRadioGroup v-model={formValues.regularState}>
                {orderState.orderQualityServiceSelectList?.value?.map(
                  (item: orderQualityServiceEnum) => (
                    <ElRadio key={item?.key} label={item?.key}>
                      {item?.value}
                    </ElRadio>
                  )
                )}
              </ElRadioGroup>
            </ElFormItem>
            <ElFormItem
              label="归档说明"
              prop="regularMemo"
              rules={[{ required: true, message: '请输入归档说明', trigger: 'change' }]}
            >
              <InputTextarea
                v-model:inputTextareaValue={formValues.regularMemo}
                placeholderName="请输入归档说明"
                limitLength={100}
              />
            </ElFormItem>
          </ElForm>
        </ElDialog>
      )}
      {/* 工单保存 编辑 */}
      {clickOptionButtonType?.identType === 'order_update' && (
        <OrdersUpdate
          title="编辑工单(待办)"
          showOrdersUpdate={visibleRef.value}
          info={detail}
          cancel={props.cancel}
          onHandleClose={props.clearClickOptionButtonType}
        />
      )}
      {/* 工单发送 */}
      {clickOptionButtonType?.identType === 'order_send' && handleOrderSend()}
      {/* 工单删除 */}
      {clickOptionButtonType?.identType === 'order_delete' && handleOrderDelete()}
      {/* 完成计划 */}
      {!clickOptionButtonType?.identType &&
        clickOptionButtonType?.type === 'agree' &&
        handleCompletePlan()}
    </>
  )
}
